<template>
  <basic-container>
    <avue-crud
      :option="option"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :table-loading="loading"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @selection-change="selectionChange"
      row-key="onlyId"
      :key="timer"
    >
      <template slot="menu" slot-scope="{ row }">
        <el-button @click="detailEvent(row)" type="text" size="small" icon="el-icon-view">详 情</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" size="small" @click="sendInspection">发起检验</el-button>
      </template>
    </avue-crud>
    <el-dialog append-to-body :visible.sync="flagDialog" title="详情">
      <avue-crud ref="crud2" :option="optionDialog" :data="dataDialog" :table-loading="packDetailLoading">
        <!-- <template slot-scope="{ row }" slot="packStatus">
          <span>
            {{ row.packStatus | statusConvert(val) }}
          </span>
        </template>
        <template slot-scope="{ row }" slot="packSubType">
          <span>
            {{ row.packSubType === 'HISTORY_MATERIAL' ? '历史物料' : '正常' }}
          </span>
        </template> -->
        <template slot="menu" slot-scope="{ row }">
          <el-button @click="detailEvent2(row)" type="text" size="small" icon="el-icon-view">详 情</el-button>
        </template>
      </avue-crud>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getInventoryInfo, getDetail, submit } from '@/api/warehouse/material-inspection';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  components: {
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    let optionObj = {
      height: 'calc(100vh - 400px)',
      calcHeight: 30,
      delBtn: false,
      editBtn: false,
      addBtn: false,
      refreshBtn: false, //刷新按钮是否显示
      columnBtn: false, //控制表格列是否显示按钮是否显示
      border: true
    };
    return {
      pageCode: 'MATERIAL_INSPECTION',
      form: {},
      query: {},
      loading: true,
      inventoryType: '',
      timer: new Date().getTime(),
      packDetailLoading: true,
      packDetailLoading2: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      params: {},
      selectionList: [],
      flagDialog: false,
      flagDialog2: false,
      StockLabel: '',
      options: [],
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchMenuSpan: 4,
        refreshBtn: true, //刷新按钮是否显示
        searchBtn: true, // 显示查询的按钮
        searchSpan: 4,
        border: true,
        index: false,
        dialogClickModal: false,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        viewBtn: false,
        width: '100',
        searchLabelWidth: 100,
        searchMenuPosition: 'right',
        searchShow: true,
        selection: true,
        columnBtn: false,
        // indexLabel: '序号',
        column: [
          // {
          //   label: '库存中心',
          //   prop: 'inventoryName',
          //   type: 'select',
          //   search: true,
          //   hide: true,
          //   dicUrl: '/api/mes-admin/inventory/list',
          //   props: {
          //     label: 'name',
          //     value: 'id'
          //   },
          //   cascader: ['areaName']
          // },
          // // {
          // //   label: '库存中心',
          // //   prop: 'inventoryId',
          // //   search: true,
          // //   searchOrder: 2,
          // //   type: 'select',
          // //   hide: true,
          // //   dicUrl: '/api/mes-admin/inventory/list',
          // //   props: {
          // //     label: 'name',
          // //     value: 'id'
          // //   },
          // //   cascader: ['areaId']
          // // },
          // {
          //   label: '储位编码',
          //   prop: 'areaCode',
          //   hide: true
          // },
          // {
          //   label: '选择储位',
          //   prop: 'areaId',
          //   type: 'select',
          //   search: true,
          //   hide: true,
          //   dicUrl: '/api/mes-admin/area/select/inventory?inventoryId={{key}}',
          //   props: {
          //     label: 'name',
          //     value: 'id'
          //   },
          //   dicFlag: false
          // },
          // {
          //   label: '选择储位',
          //   prop: 'areaName',
          //   type: 'select',
          //   search: true,
          //   hide: true,
          //   dicUrl: '/api/mes-admin/area/select/inventory?inventoryId={{key}}',
          //   props: {
          //     label: 'name',
          //     value: 'id'
          //   },
          //   dicFlag: false
          // },
          {
            label: '物料编码',
            prop: 'partNo',
            search: true,
            span: 4
          },
          {
            label: '物料名称',
            prop: 'partMasterName',
            search: true
          },
          {
            label: '物料批次',
            prop: 'lotNo'
          },
          {
            label: '物料数量',
            prop: 'partMasterCount',
            type: 'number',
            precision: 10
          },
          {
            label: '生产日期',
            prop: 'vendorDate'
          },
          {
            label: '物料保质期天数',
            prop: 'expirationDays'
          },
          {
            label: '过期时间',
            prop: 'expirationDate'
          },
          {
            label: '剩余天数',
            prop: 'overdueDays'
          }
        ]
      },
      optionDialog: {
        ...optionObj,
        menuWidth: 100,
        menu: false, //表格操作栏是否显示
        column: [
          {
            label: '包装条码',
            prop: 'sequenceNumber',
            span: 6
          },
          {
            label: '包装数量',
            prop: 'quantity',
            span: 6
          },
          {
            label: '物料批次',
            prop: 'lotNo',
            span: 6
          },
          {
            label: '供应商编码',
            prop: 'code',
            span: 6
          },
          {
            label: '供应商名称',
            prop: 'partnerName'
          },
          {
            label: '库存中心',
            prop: 'inventoryName'
          },
          {
            label: '储位编码',
            prop: 'areaCode'
          },
          {
            label: '储位名称',
            prop: 'areaName'
          }
        ]
      },
      data: [],
      dataDialog: [],
      dataDialog2: []
    };
  },
  filters: {
    // statusConvert(val) {
    //   switch (val) {
    //     case 1:
    //       return '正常';
    //     case 2:
    //       return '全部锁定';
    //     case 3:
    //       return '部分锁定';
    //     case 4:
    //       return '报废';
    //     case 5:
    //       return '已出库';
    //     case 6:
    //       return '已入库';
    //     default:
    //       break;
    //   }
    // }
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.material_view, false),
        addBtn: this.vaildData(this.permission.material_add, false),
        delBtn: this.vaildData(this.permission.material_delete, false),
        editBtn: this.vaildData(this.permission.material_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    init() {},
    detailEvent(row) {
      this.flagDialog = true;
      getDetail({
        partNo: row.partNo,
        lotNo: row.lotNo,
        expirationDate: row.expirationDate
      }).then((res) => {
        this.packDetailLoading = true;
        if (res.data.data) {
          this.dataDialog = res.data.data;
          this.packDetailLoading = false;
        }
      });
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          console.log(row, 'rwoew');
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset(params, done) {
      this.query = {};
      this.page.currentPage = 1;
      this.page.pageSize = 15;
      this.onLoad(this.page, this.query);
    },
    searchChange(params, done) {
      if (params.inventoryName) {
        params.inventoryId = params.inventoryName;
        delete params.inventoryName;
      }
      if (params.areaName) {
        params.areaId = params.areaName;
        delete params.areaName;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, this.query);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page, this.params);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data ? (data.total ? data.total : '') : '';
        this.data = data.records || [];
        this.loading = false;
      });
    },
    sendInspection() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定是否发起检验', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let packingList = this.selectionList.map((item) => {
            return {
              partNo: item.partNo,
              expirationDate: item.expirationDate,
              lotNo: item.lotNo
            };
          });
          let params = {
            documentType: 'ODQC',
            packingList
          };
          return submit(params);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  watch: {}
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}
::v-deep .el-dialog__body {
  padding: 15px 24px;
  .avue-crud__menu {
    display: none;
  }
}
</style>
